<template>
  <el-upload
    v-show="false"
    ref="upload"
    class="upload-demo"
    :headers="headers"
    :action="actionUrl"
    :limit="1"
    v-bind="$attrs"
    :on-success="successUp"
    :on-error="errorUp"
    :before-upload="beforUpload"
  >
    <el-button ref="files" size="small" type="primary" />
  </el-upload>
</template>

<script>

export default {
  name:'ImportFile',
  props: {
    uploadApi: { require: true, type: String, default: '' }
  },
  data() {
    return {
      headers: {
        Authorization: 'Bearer ' + sessionStorage.getItem('token')
      },
      resultVisible: false,
      importRecord: {}
    }
  },
  computed: {
    actionUrl() {
      return process.env.VUE_APP_BASE_API + this.uploadApi
    }
  },
  methods: {
    // 导入
    async importHandel() {
      this.$refs.upload.clearFiles()
      this.$refs.files.$parent.handleClick()
    },
    beforUpload(file) {
      this.loading = this.$loading({
        lock: true,
        text: '文件导入中。。。',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const size = (file.size / 1024 / 1024).toFixed(2) < 30
      if (!size) {
        this.$confirm('文件大于30M,请重新选择上传文件', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false
        }).then(() => {
          this.$refs.upload.clearFiles()
          this.$refs.files.$parent.handleClick()
        })
      }
      return size
    },
    errorUp() {
      this.loading.close()
      this.$alert('文件导入失败', '导入结果', {
        type: 'error'
      })
    },
    successUp(res) {
      this.loading.close()
      let message = ''
      let type = ''
      if (res.code === '200') {
        if (res.record.fails) {
          this.$emit('onSuccess', res.record)
          return
        } else {
          // 失败=0
          message = `${res.msg}，成功${res.record.success}条，失败${res.record.fails}条`
          type = 'success'
          this.$emit('onSuccess', 'success')
        }
      } else {
        message = res.msg
        type = 'error'
      }
      this.$alert(message, '导入结果', {
        dangerouslyUseHTMLString: true,
        type: type
      })
    }
  }
}
</script>
